from rest_framework import status
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response

from utils.unite.code import *

SUCCESS_INFO = u'请求成功'
DEFAULT_CODE_SUCCESS = 200
DEFAULT_CODE_ERROR = 203
DEFAULT_CODE_VALIDATE = 204
DEFAULT_CODE_TOKEN = 401

"""
    @TODO 请求返回封装
    1. 自己封装一套,要处理蛮多东西
        {
            1.自定义分页
            2.自定义请求
            3.返回error 捕捉
            4.使用django的ApiView
        }
    2. 使用django一套
        {
            1.判断status_code (一定要设置到 status 最重要****)
            2.判断detail
        }
"""


def ApiResponse(code=DEFAULT_SUCCESS, message=SUCCESS_INFO, data=None, status=status.HTTP_200_OK, headers=None):
    """
    请求返回统一封装
    :param code:
    :param message:
    :param data:
    :param status:
    :param headers:
    :return:
    """
    err = {
        'code': code,
        'message': message,
        'results': data
    }
    return Response(err, status, headers=headers)


def get_serializer_error(errors):
    """
    serializers error 取值第一个 返回
    :param errors:
    :return:
    """
    message = "参数错误:"
    for key in errors:
        message += errors[key][0]
        break
    return message


class CustomPagination(LimitOffsetPagination):
    """
    自定义分页
    """

    def get_paginated_response(self, data):
        return Response({
            'code': DEFAULT_SUCCESS,
            'message': SUCCESS_INFO,
            'results': {
                'links': {
                    'next': self.get_next_link(),
                    'previous': self.get_previous_link()
                },
                'total': self.count,
                'list': data,
                'limit': self.limit,
                'offset': self.offset,
            }
        })
